// 通用的与后端建立连接的方法
let socket;

// 建立链接
export function connectWebSocket(data) {
  console.log(data, 'data');
  return new Promise((resolve, reject) => {
    // 假设后端 WebSocket 服务路径为 /ws，并且添加协议前缀
    const socketUrl = `${process.env.VUE_APP_BASE_URL_IP}/ws?userId=${data.userId}`;
    console.log(socketUrl, "socketUrl");

    try {
      socket = new WebSocket(socketUrl);

      socket.onopen = () => {
        console.log("WebSocket 连接已建立");
        resolve(socket);
      };

      socket.onmessage = (event) => {
        const message = event.data;
        console.log(message, "message");
      };

      socket.onclose = () => {
        console.log("WebSocket 连接已关闭");
      };

      socket.onerror = (error) => {
        console.error("WebSocket 连接错误:", error);
        reject(error);
      };
    } catch (error) {
      console.log(error, "error");
      reject(error);
    }
  });
}

// 发送消息
export function sendWebSocketMessage(targetUserId, content) {
  if (socket && socket.readyState === WebSocket.OPEN) {
    const message = JSON.stringify({
      targetUserId,
      content
    });
    socket.send(message);
  } else {
    console.error("WebSocket 连接未建立或已关闭，无法发送消息");
  }
}

// 关闭链接
export function closeWebSocket() {
  console.log("关闭链接");
  if (socket) {
    socket.close();
  }
}